package com.hcl.security.handle;

import java.io.IOException;
import java.io.PrintWriter;

import com.hcl.security.utils.JsonUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.hcl.security.utils.Result;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 用于处理权限不足的情况
 */
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException)
			throws IOException, ServletException {
		// 设置响应内容类型为JSON，字符编码为UTF-8
		response.setContentType("application/json;charset=UTF-8");
		// 设置响应状态码为403，表示权限不足
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		// 获取响应的输出流
		PrintWriter writer = response.getWriter();
		// 输出JSON格式的错误信息
		writer.println(JsonUtils.objectToJson(
				Result.error(HttpServletResponse.SC_FORBIDDEN, "权限不足")));
		// 刷新输出流
		writer.flush();
		// 关闭输出流
		writer.close();
	}
}
